package alertScene

import (
	"context"
	"devops-super/api"
	"devops-super/api/alerts/v1"
	"devops-super/internal/dao"
	"devops-super/internal/model/entity"
	"devops-super/internal/model/mymodel"
	"devops-super/internal/service"
	"devops-super/utility/util/arrayUtil"
	"errors"
	"github.com/gogf/gf/v2/os/glog"
	"time"
)

type sAlertScene struct{}

var cols = dao.AlertScene.Columns()

func init() {
	service.RegisterAlertScene(New())
}

func New() *sAlertScene {
	return &sAlertScene{}
}

// Add 添加告警场景
func (*sAlertScene) Add(ctx context.Context, in *entity.AlertScene) (err error) {
	// 检查名称是否已存在
	count, _ := dao.AlertScene.Ctx(ctx).Where(cols.Name, in.Name).Count()
	if count > 0 {
		return errors.New("告警场景名称已存在")
	}

	_, err = dao.AlertScene.Ctx(ctx).Insert(in)
	return
}

// Upt 更新告警场景
func (*sAlertScene) Upt(ctx context.Context, in *entity.AlertScene) (err error) {
	// 检查名称是否已存在（排除当前记录）
	count, _ := dao.AlertScene.Ctx(ctx).Where(cols.Name, in.Name).Where(cols.Id+" != ?", in.Id).Count()
	if count > 0 {
		return errors.New("告警场景名称已存在")
	}

	_, err = dao.AlertScene.Ctx(ctx).WherePri(in.Id).OmitNilData().Data(in).Update()
	return
}

// GetPageLst 分页获取告警场景列表
func (*sAlertScene) GetPageLst(ctx context.Context, req *v1.AlertSceneGetPageLstReq) (out *v1.AlertSceneGetPageLstRes, err error) {
	out = &v1.AlertSceneGetPageLstRes{}
	out.PageLstRes = &api.PageLstRes[*mymodel.AlertSceneResponse]{}
	m := dao.AlertScene.Ctx(ctx).Safe(true)

	// 名称模糊查询
	if req.Name != "" {
		m = m.Where(cols.Name+" like ?", "%"+req.Name+"%")
	}

	// 类型筛选
	if req.Type != "" {
		m = m.Where(cols.Type, req.Type)
	}

	// 部门筛选
	if req.DeptId != "" {
		m = m.Where(cols.DeptId, req.DeptId)
	}

	// 按时间范围筛选
	if req.TimeRange != nil && len(req.TimeRange) == 2 {
		// 新增时间转换逻辑
		startTime, err := time.Parse(time.RFC3339, req.TimeRange[0])
		if err != nil {
			return nil, errors.New("开始时间格式错误")
		}
		endTime, err := time.Parse(time.RFC3339, req.TimeRange[1])
		if err != nil {
			return nil, errors.New("结束时间格式错误")
		}
		timeLayout := "2006-01-02 15:04:05"
		timeStr0 := startTime.Local().Format(timeLayout)
		timeStr1 := endTime.Local().Format(timeLayout)
		m = m.WhereBetween(cols.CreatedAt, timeStr0, timeStr1)
	}

	// 分页查询原始实体
	var entities []*entity.AlertScene
	if err = m.Offset(req.Offset()).Limit(req.Limit()).ScanAndCount(&entities, &out.Total, false); err != nil {
		return
	}

	deptIds := make([]int64, 0)
	for _, item := range entities {
		if !arrayUtil.IsExistsItem(item.DeptId, deptIds) {
			deptIds = append(deptIds, int64(item.DeptId))
		}
	}
	var deptResults []*entity.Dept
	_ = dao.Dept.Ctx(ctx).WhereIn(dao.Dept.Columns().Id, deptIds).Scan(&deptResults)

	// 转换为响应模型
	out.List = make([]*mymodel.AlertSceneResponse, len(entities))
	for i, e := range entities {
		deptName := ""
		for _, result := range deptResults {
			if result.Id == int(e.DeptId) {
				deptName = result.Name
			}
		}

		out.List[i] = &mymodel.AlertSceneResponse{
			Id:          e.Id,
			Name:        e.Name,
			EnglishName: e.EnglishName,
			Type:        e.Type,
			DeptId:      e.DeptId,
			Level:       e.Level,
			Frequency:   e.Frequency,
			NoticeType:  e.NoticeType,
			Remark:      e.Remark,
			CreatedAt:   e.CreatedAt,
			UpdatedAt:   e.UpdatedAt,
			BindTo:      e.BindTo,
			JudgeMark:   e.JudgeMark,
			DeptName:    deptName,
		}
	}
	return
}

// UptStatus 更新告警场景状态
func (*sAlertScene) UptStatus(ctx context.Context, id uint64, status int) (err error) {
	return
}

// Del 删除告警场景
func (*sAlertScene) Del(ctx context.Context, id uint64) (err error) {
	// 可以在这里添加业务校验，例如检查是否有相关联的数据
	number1, _ := dao.AlertPeopleToScene.Ctx(ctx).Where(dao.AlertPeopleToScene.Columns().SceneId, id).Count()
	if number1 > 0 {
		err = errors.New("cannot delete a bound person scene")
		return
	}

	number2, _ := dao.AlertDeviceToScene.Ctx(ctx).Where(dao.AlertDeviceToScene.Columns().SceneId, id).Count()
	if number2 > 0 {
		err = errors.New("cannot delete a bound device scene")
		return
	}

	number3, _ := dao.AlertDevicegroupToScene.Ctx(ctx).Where(dao.AlertDevicegroupToScene.Columns().SceneId, id).Count()
	if number3 > 0 {
		err = errors.New("cannot delete a bound device-group scene")
		return
	}

	_, err = dao.AlertScene.Ctx(ctx).WherePri(id).Delete()
	return
}

// GetOne 获取单个告警场景
func (*sAlertScene) GetOne(ctx context.Context, id uint64) (out *entity.AlertScene, err error) {
	out = &entity.AlertScene{}
	err = dao.AlertScene.Ctx(ctx).WherePri(id).Scan(&out)
	return
}

// GetOptions 获取告警场景选项
func (*sAlertScene) GetOptions(ctx context.Context, in *v1.AlertSceneGetOptionsReq) (out *v1.AlertSceneGetOptionsRes, err error) {
	out = new(v1.AlertSceneGetOptionsRes)
	var data []*entity.AlertScene
	m := dao.AlertScene.Ctx(ctx)
	if in.DeptId > 0 {
		m = m.Where(cols.DeptId, in.DeptId)
	}
	superDept, currentUser, _ := service.User().IsCurrentUserSuperDept(ctx)
	if !superDept {
		m = m.Where(cols.DeptId, currentUser.DeptId)
	}
	err = m.Scan(&data)
	if err != nil {
		glog.Line().Error(ctx, err)
		return
	}
	out.Options = make([]*api.FormOptionsItem, 0)
	if data != nil {
		for _, v := range data {
			out.Options = append(out.Options, &api.FormOptionsItem{
				Value: v.Id,
				Label: v.Name + "(" + v.EnglishName + ")",
			})
		}
	}
	return
}
